//
//  BloodSugarViewController.m
//  安好
//
//  Created by 马晓良 on 14-11-26.
//  Copyright (c) 2014年 lianchuangbrother. All rights reserved.
//

#import "BloodSugarViewController.h"
#import "BasicSignsCell.h"
//#import "EditImportSignsViewController.h"
#import "BloodSugarEditViewController.h"
@interface BloodSugarViewController ()<UITableViewDataSource,UITableViewDelegate,UITextFieldDelegate>
{
    BOOL isHaveDian;
}
/**
 *  血糖tableView
 */
@property (strong, nonatomic) IBOutlet UITableView *bloodSugarTableView;
/**
 *  存放cell前的类型
 */
@property (nonatomic, strong) NSArray *bloodSugerTypeArray;
/**
 *  上传的字典
 */
@property (nonatomic, strong) NSMutableDictionary *uploadDic;
@end

@implementation BloodSugarViewController

- (NSMutableDictionary *)uploadDic{
    if (_uploadDic == nil) {
        self.uploadDic = [NSMutableDictionary dictionary];
    }
    return _uploadDic;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.bloodSugarTableView.dataSource = self;
    self.bloodSugarTableView.delegate = self;
    self.bloodSugerTypeArray = @[@"日期",@"餐后",@"空腹"];
    [self  setNaviBarAttribute];
    self.bloodSugarTableView.backgroundColor = [ClassMethodsViewController colorWithHexString:BACK_BACKGROUNDCOLOR_16];
    self.navigationItem.title = @"血糖";
    // Do any additional setup after loading the view from its nib.
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
//    self.navigationController.navigationBar.translucent = NO;
}



- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
//    self.navigationController.navigationBar.translucent = YES;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


#pragma mark - 设置naviBar 并实现左右naviBar button方法 -
- (void)setNaviBarAttribute{
    /**
     *  设置左NaviBar和右naviBar
     */
    UIButton *leftButton = [UIButton buttonWithType:UIButtonTypeCustom];
    leftButton.frame = CGRectMake(0, 0, 23, 23);
    [leftButton setImage:[UIImage imageNamed:@"公用_返回"] forState:UIControlStateNormal];
    [leftButton addTarget:self action:@selector(handleLeftButtonAction) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:leftButton];
    self.navigationItem.leftBarButtonItem = leftBarButtonItem;
    
    
    UIButton *rightButton = [UIButton buttonWithType:UIButtonTypeCustom];
    rightButton.frame = CGRectMake(0, 0, 30, 23);
    //    [rightButton setImage:[UIImage imageNamed:@"公用_完成"] forState:UIControlStateNormal];
    [rightButton setTitle:@"添加" forState:UIControlStateNormal];
    rightButton.titleLabel.font = [UIFont systemFontOfSize:15];
    [rightButton addTarget:self action:@selector(handleRightButtonAction) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:rightButton];
}

/**
 *  返回主页面
 */
- (void)handleLeftButtonAction{
    [self.navigationController popViewControllerAnimated:YES];
}

/**
 *  完成(返回并传值)
 */
- (void)handleRightButtonAction{
    if ([self getCellTextFieldText]) {
        [self _parsePersonalDataSource:kBaseURL];
    }else{
        alertContent(@"血糖的范围在0.00-80.00mmol/L");
    }
    
}

#pragma mark - tableView的代理方法 -
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 2;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 0) {
        return 3;
    }else{
        return 1;
    }
}


- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section == 0) {
        return 10;
    }else{
        return 20;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (kScreenWidth == 414) {
        return 54;
    }else{
        return 44;
    }
}


- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.5;
}



- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    BasicSignsCell *cell = [tableView dequeueReusableCellWithIdentifier:@"basicSignsCell"];
    if (!cell) {
        if (kScreenWidth == 414) {
            cell = [[[NSBundle mainBundle] loadNibNamed:@"BasicSignsCell" owner:self options:nil] lastObject];
        }else{
            cell = [[[NSBundle mainBundle] loadNibNamed:@"BasicSignsCell" owner:self options:nil] firstObject];
        }
    }
    if(indexPath.section == 0){
        cell.signsTypeLabel.text = self.bloodSugerTypeArray[indexPath.row];
        cell.signsDataTextField.keyboardType = UIKeyboardTypeNumbersAndPunctuation;
        cell.signsDataTextField.delegate = self;
        if (indexPath.row == 0) {
            cell.signsDataTextField.enabled = NO;
            cell.signsDataTextField.text = self.timeStr;
            cell.jumpImageView.hidden = YES;
        }else if(indexPath.row == 1){
            [cell.signsDataTextField becomeFirstResponder];
            UILabel *label = [[UILabel alloc] init];
            if (kScreenWidth == 414) {
                label.frame = CGRectMake(0, 0, 52, 18);
            }else{
                label.frame = CGRectMake(0, 0, 48, 18);
            }
            label.font = [UIFont systemFontOfSize:LABEL_FONT_SIZE_CONTENT_13];
            label.text = @"mmol/L";
            label.textColor = [UIColor lightGrayColor];
            cell.signsDataTextField.rightView = label;
            cell.signsDataTextField.rightViewMode = UITextFieldViewModeAlways;
            cell.signsDataTextField.text = @"";
            cell.jumpImageView.hidden = YES;
        }else{
            UILabel *label = [[UILabel alloc] init];
            if (kScreenWidth == 414) {
                label.frame = CGRectMake(0, 0, 52, 18);
            }else{
                label.frame = CGRectMake(0, 0, 48, 18);
            }
            label.font = [UIFont systemFontOfSize:LABEL_FONT_SIZE_CONTENT_13];
            label.text = @"mmol/L";
            label.textColor = [UIColor lightGrayColor];
            cell.signsDataTextField.rightView = label;
            cell.signsDataTextField.rightViewMode = UITextFieldViewModeAlways;
            cell.signsDataTextField.text = @"";
            cell.jumpImageView.hidden = YES;
        }
    }else if (indexPath.section == 1){
        cell.signsDataTextField.text = @"";
        cell.signsDataTextField.enabled = NO;
    }
    return cell;
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 1) {
        BloodSugarEditViewController *bloodsugarVC = [[BloodSugarEditViewController alloc] init];
        bloodsugarVC.naviTitleStr = self.navigationItem.title;
        [self.navigationController pushViewController:bloodsugarVC animated:YES];
    }
}


#pragma mark - 网路数据上传 -
- (void)_parsePersonalDataSource:(NSString *)urlString{
    [self showActionView];
    NSString *time = [self setNewTime];
    
    // 获取url地址
    NSString * postURL = [NSString stringWithFormat:@"%@user/logadd/",urlString];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [self.uploadDic setValue:kPlatform forKey:@"platform"];
    [self.uploadDic setValue:kVersion forKey:@"version"];
    [self.uploadDic setValue:@"9" forKey:@"type"];
    [self.uploadDic setValue:time forKey:@"daytime"];
    [manager POST:postURL parameters:self.uploadDic success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSNumber * statusNum = [responseObject objectForKey:@"status"];
        NSNumberFormatter* numberFormatter = [[NSNumberFormatter alloc] init];
        NSString * statusString = [numberFormatter stringFromNumber:statusNum];
        [self hiddenActionView];
        if ([statusString isEqualToString:@"0"]) {
            [self showCustomHudSingleLine:@"上传失败"];
        }else{
            MyNSLog("========%@========", [responseObject objectForKey:@"msg"]);
            [self.navigationController popViewControllerAnimated:YES];
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"%@",error);
        MyNSLog("网络失败");
        [self hiddenActionView];
    }];
}


#pragma mark - 获取cell中的textField - 
- (BOOL)getCellTextFieldText{
    NSInteger k1;
    NSInteger k2;
    NSInteger sum;
    NSIndexPath *pathOne=[NSIndexPath indexPathForRow:1 inSection:0];//获取cell的位置
    BasicSignsCell *cellOne= (BasicSignsCell *)[self.bloodSugarTableView cellForRowAtIndexPath: pathOne];
    if ([cellOne.signsDataTextField.text floatValue] > 80) {
        cellOne.signsDataTextField.text = @"";
        k1 = -1;
    }else if ([cellOne.signsDataTextField.text isEqualToString:@""]){
        k1 = 0;
    }else{
        [self.uploadDic setValue:cellOne.signsDataTextField.text forKey:@"ppbs"];
         k1 = 1;
    }
    
    NSIndexPath *pathTwo=[NSIndexPath indexPathForRow:2 inSection:0];//获取cell的位置
    BasicSignsCell *cellTwo= (BasicSignsCell *)[self.bloodSugarTableView cellForRowAtIndexPath: pathTwo];
    if ([cellTwo.signsDataTextField.text floatValue] > 80) {
        cellTwo.signsDataTextField.text = @"";
        k2 = -1;
    }else if ([cellTwo.signsDataTextField.text isEqualToString:@""]){
        k2 = 0;
    }else{
        [self.uploadDic setValue:cellTwo.signsDataTextField.text forKey:@"ppbg"];
        k2 = 1;
    }
    
    sum = k1 + k2;
    if (sum >=1) {
        return YES;
    }else{
        return NO;
    }
}

#pragma mark - 获取当前的时间 -
- (NSString *)setNewTime{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"YYYY-MM-dd"];
    NSString *locationString=[formatter stringFromDate: [NSDate date]];
    return locationString;
    
}

//- (NSString *)setNewTime{
//    NSDate *now = [NSDate date];
//    NSCalendar *calendar = [NSCalendar currentCalendar];
//    NSUInteger unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
//    NSDateComponents *dateComponent = [calendar components:unitFlags fromDate:now];
//    int year = [dateComponent year];
//    int month = [dateComponent month];
//    int day = [dateComponent day];
//    
//    NSString *time = [NSString stringWithFormat:@"%d-%d-%d",year,month,day];
//    MyNSLog("%@",time);
//    return time;
//}

#pragma mark - textField的代理方法 -
- (BOOL)textFieldShouldReturn:(UITextField *)textField;
{
    //用户结束输入
    [textField resignFirstResponder];
    return YES;
}

//textField.text 输入之前的值         string 输入的字符
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    BasicSignsCell *cell = nil;
    UIView  *view = textField.superview;
    for (NSInteger i = 0; i < 1; ) {
        if ([view isKindOfClass:[BasicSignsCell class]]) {
            cell = (BasicSignsCell *)view;
            break;
        }else{
            view =view.superview;
        }
    }
    
    NSInteger length = (NSInteger)cell.signsDataTextField.text.length;
    if (length >= 5  &&  string.length >0)
    {
        return  NO;
    }
    
    
    if ([cell.signsDataTextField.text rangeOfString:@"."].location == NSNotFound) {
        isHaveDian = NO;
    }
    
    if ([string length]>0)
    {
        unichar single=[string characterAtIndex:0];//当前输入的字符
        if ((single >='0' && single<='9') || single=='.')//数据格式正确
        {
            //首字母不能为0和小数点
            if([cell.signsDataTextField.text length]==0){
                if(single == '.'){
                    MyNSLog("亲，第一个数字不能为小数点");
                    [cell.signsDataTextField.text stringByReplacingCharactersInRange:range withString:@""];
                    return NO;
                    
                }
                if (single == '0') {
                    MyNSLog("亲，第一个数字不能为0");
                    [cell.signsDataTextField.text stringByReplacingCharactersInRange:range withString:@""];
                    return NO;
                }
                
            }
            if (single=='.')
            {
                if(!isHaveDian)//text中还没有小数点
                {
                    isHaveDian=YES;
                    return YES;
                }else
                {
                    MyNSLog("亲，您已经输入过小数点了");
                    [cell.signsDataTextField.text stringByReplacingCharactersInRange:range withString:@""];
                    return NO;
                }
            }
            else
            {
                if (isHaveDian)//存在小数点
                {
                    //判断小数点的位数
                    NSRange ran=[cell.signsDataTextField.text rangeOfString:@"."];
                    NSInteger tt= (NSInteger) (range.location-ran.location);
                    if (tt <= 2){
                        return YES;
                    }else{
                        MyNSLog("亲，您最多输入两位小数");
                        return NO;
                    }
                }
                else
                {
                    return YES;
                }
            }
        }else{//输入的数据格式不正确
            MyNSLog("亲，您输入的格式不正确");
            [cell.signsDataTextField.text stringByReplacingCharactersInRange:range withString:@""];
            return NO;
        }
    }
    else
    {
        return YES;
    }
    
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
